package test.org.example.java.io;

import org.junit.Test;

import java.io.*;

/**
 * User: ZhangJuntao
 * Date: 14-2-25
 * Time: 上午9:10
 */
public class BufferedReaderWriter {
  @Test
  public void writeToFile() throws Exception {
    File file = new File("data/api-2013-08-24.log");
    writeToFile(file);
  }

  @Test
  public void readFile() throws Exception {
    File file = new File("data/api-2013-08-24.log");
    readFile(file);
  }

  private void readFile(File file) throws IOException {
    //    BufferedReader reader = new BufferedReader(new FileReader(file));
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
    String str;
    System.out.println("读取中，文件的内容如下：");
    while ((str = reader.readLine()) != null) {
      System.out.println(str);
    }
  }

  /**
   * Prints some data to a file using a BufferedWriter
   */
  public void writeToFile(File file) {
    BufferedWriter bufferedWriter = null;
    try {
      bufferedWriter = new BufferedWriter(new FileWriter(file, false));
      bufferedWriter.write("hello world");
      bufferedWriter.newLine();
      bufferedWriter.write("hello hans");
      bufferedWriter.newLine();

    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      try {
        if (bufferedWriter != null) {
          bufferedWriter.flush();
          bufferedWriter.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
}
